package com.mogujie.tt.ui.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.mogujie.tt.DB.DBInterface;
import com.mogujie.tt.DB.entity.DepartmentEntity;
import com.mogujie.tt.DB.entity.UserEntity;
import com.mogujie.tt.DB.sp.LoginSp;
import com.mogujie.tt.DB.sp.RegisterSp;
import com.mogujie.tt.R;
import com.mogujie.tt.config.DBConstant;
import com.mogujie.tt.config.IntentConstant;
import com.mogujie.tt.config.NewFriendsConstant;
import com.mogujie.tt.config.RegisterConstant;
import com.mogujie.tt.config.SysConstant;
import com.mogujie.tt.imservice.event.ConcurrentUserDetailsEvent;
import com.mogujie.tt.imservice.manager.IMContactManager;
import com.mogujie.tt.imservice.manager.IMNewFriendsManager;
import com.mogujie.tt.ui.activity.SentAddMessageActivity;
import com.mogujie.tt.utils.IMUIHelper;
import com.mogujie.tt.imservice.event.UserInfoEvent;
import com.mogujie.tt.imservice.manager.IMLoginManager;
import com.mogujie.tt.imservice.service.IMService;
import com.mogujie.tt.ui.activity.DetailPortraitActivity;
import com.mogujie.tt.imservice.support.IMServiceConnector;
import com.mogujie.tt.ui.widget.IMBaseImageView;
import com.mogujie.tt.utils.ImageUtil;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;

import de.greenrobot.event.EventBus;

/**
 * 1.18 添加currentUser变量
 */
public class UserInfoFragment extends MainFragment {

	private View curView = null;
    private IMService imService;
    private UserEntity currentUser;//用户实体
    private int currentUserId;
	private int currentAddUser;
	private DBInterface dbInterface = DBInterface.instance();//读取本地数据库
    private IMServiceConnector imServiceConnector = new IMServiceConnector(){
        @Override
        public void onIMServiceConnected() {
            logger.d("detail#onIMServiceConnected");

            imService = imServiceConnector.getIMService();//得到服务
            if (imService == null) {
                logger.e("detail#imService is null");
                return;
            }

			currentAddUser =getActivity().getIntent().getIntExtra(IntentConstant.KEY_ADDUSER,0);

            currentUserId = getActivity().getIntent().getIntExtra(IntentConstant.KEY_PEERID,0);//得到用户ID
            if(currentUserId == 0){
                logger.e("detail#intent params error!!");
                return;
            }
			if(currentAddUser ==1&&dbInterface.getByLoginId(currentUserId) == null){
				currentUser =NewFriendsConstant.userFind;
				if (currentUser != null) {
					initBaseProfile();//设置头像
					initDetailProfile();//设置详细信息
				}
			}else {
			//	currentUser = imService.getContactManager().findContact(currentUserId);//从本地数据库中加载数据
				currentUser = dbInterface.getByLoginId(currentUserId);//从本地数据库中加载数据
			//	Log.v("UserInfoFragment", "currentUser = "+currentUser);
				if (currentUser != null) {
					initBaseProfile();//设置头像
					initDetailProfile();//设置详细信息

				}
				ArrayList<Integer> userIds = new ArrayList<>(1);
				//just single type
				userIds.add(currentUserId);
				imService.getContactManager().reqGetDetaillUsers(userIds);
			}
			if(currentUserId == LoginSp.instance().getLoginIdentity().getLoginId()){
				synchronousDetails();//更改详细信息
			}
        }
        @Override
        public void onServiceDisconnected() {}
    };

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		imServiceConnector.disconnect(getActivity());
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public void onStart() {
		super.onStart();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		imServiceConnector.connect(getActivity());
		if (null != curView) {
			((ViewGroup) curView.getParent()).removeView(curView);
			return curView;
		}
		curView = inflater.inflate(R.layout.tt_fragment_user_detail, topContentView);
		super.init(curView);
		showProgressBar();
		initRes();
		return curView;
	}

	@Override
	public void onResume() {
		Intent intent = getActivity().getIntent();
		if (null != intent) {
			String fromPage = intent.getStringExtra(IntentConstant.USER_DETAIL_PARAM);
			setTopLeftText(fromPage);
		}
		super.onResume();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	/**
	 * @Description 初始化资源
	 */
	private void initRes() {
		// 设置标题栏
		setTopTitle(getActivity().getString(R.string.page_user_detail));
		setTopLeftButton(R.drawable.tt_top_back);
		topLeftContainerLayout.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				getActivity().finish();
			}
		});
		setTopLeftText(getResources().getString(R.string.top_left_back));
	}

	@Override
	protected void initHandler() {
	}

	/**
	 * 用户更新数据
	 * @param event
	 */
    public void onEventMainThread(UserInfoEvent event){
        switch (event){
            case USER_INFO_UPDATE:
                UserEntity entity  = imService.getContactManager().findContact(currentUserId);
                if(entity !=null && currentUser.equals(entity)){
                    initBaseProfile();
                    initDetailProfile();
                }

                break;
        }
    }


	private void initBaseProfile() {
		logger.d("detail#initBaseProfile");
		IMBaseImageView portraitImageView = (IMBaseImageView) curView.findViewById(R.id.user_portrait);//头像设置
		setTextViewContent(R.id.nickName, currentUser.getMainName());
		setTextViewContent(R.id.userName, currentUser.getRealName());

		portraitImageView.setDefaultImageRes(R.drawable.tt_default_user_portrait_corner);
		portraitImageView.setCorner(8);
		portraitImageView.setImageResource(R.drawable.tt_default_user_portrait_corner);
		portraitImageView.setImageUrl(currentUser.getAvatar());

		if(currentUserId == LoginSp.instance().getLoginIdentity().getLoginId()){
			portraitImageView.setDefaultImageRes(R.drawable.tt_default_user_portrait_corner);
			portraitImageView.setCorner(8);
			portraitImageView.setImageResource(R.drawable.tt_default_user_portrait_corner);
			String path = RegisterConstant.PHOTO_PATH + RegisterConstant.IMAGE_FILE_TAILOR_NAME;
			if(new File(path).exists()){
				portraitImageView.setImageUrl(RegisterSp.instance().getSpDetailedInfo().getDetailedHeadPortrait());//设置头像
			}
		}

		/*portraitImageView.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getActivity(), DetailPortraitActivity.class);
				intent.putExtra(IntentConstant.KEY_AVATAR_URL, currentUser.getAvatar());
				intent.putExtra(IntentConstant.KEY_IS_IMAGE_CONTACT_AVATAR, true);
				
				startActivity(intent);
			}
		});*/

		// 设置按钮
		Button chatBtn = (Button) curView.findViewById(R.id.chat_btn);
		if (currentUserId == imService.getLoginManager().getLoginId()) {
			chatBtn.setVisibility(View.GONE);
		}else if(currentAddUser == 1){//添加好友

			if(dbInterface.getByLoginId(currentUserId) == null){
				chatBtn.setText("添加");
			}else if(dbInterface.getByLoginId(currentUserId).getRelation() == 2){
				chatBtn.setText("同意");
			}else if(dbInterface.getByLoginId(currentUserId).getRelation() == 1){
				chatBtn.setText("等待验证");
			}
			chatBtn.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View arg0) {
					if(dbInterface.getByLoginId(currentUserId) == null){
						Intent intent = new Intent();
						intent.putExtra(IntentConstant.KEY_PEERID,currentUserId);
						intent.setClass(getActivity(), SentAddMessageActivity.class);
						getActivity().startActivity(intent);
					}else if(dbInterface.getByLoginId(currentUserId).getRelation() == 3){
						IMUIHelper.openChatActivity(getActivity(),currentUser.getSessionKey());
						getActivity().finish();
					}else if(dbInterface.getByLoginId(currentUserId).getRelation() == 2) {
						IMNewFriendsManager.instance().agreeFriendsAdd(currentUserId);
						getActivity().finish();
					}else {

					}
				}
			});
		} else if(currentAddUser ==0 ||dbInterface.getByLoginId(currentUserId) != null ){
            chatBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    IMUIHelper.openChatActivity(getActivity(),currentUser.getSessionKey());
                    getActivity().finish();
                }
            });
        }
	}

	/**
	 * 设置详细信息
	 */
	private void initDetailProfile() {
		logger.d("detail#initDetailProfile");
		hideProgressBar();

       	DepartmentEntity deptEntity1 = imService.getContactManager().getDepartmentMap().get(IMLoginManager.instance().getLoginDeptId());//得到登录用户的部门信息
		if(deptEntity1.getDepartLevel() == 0){
			curView.findViewById(R.id.DepartmentArea).setVisibility(View.GONE);
		}else {
			DepartmentEntity deptEntity2 = imService.getContactManager().findDepartment(currentUser.getDepartmentId());
			if(deptEntity2 == null||deptEntity2.getDepartLevel() == 0){
				curView.findViewById(R.id.DepartmentArea).setVisibility(View.GONE);
			}else {
				setTextViewContent(R.id.department, deptEntity2.getDepartName());//部门
			}
		}
		setTextViewContent(R.id.telno, currentUser.getPhone());//手机
		setTextViewContent(R.id.email, currentUser.getEmail());//邮箱
		setTextViewContent(R.id.sign_info,currentUser.getSigninfo());//个性签名
		View phoneView = curView.findViewById(R.id.phoneArea);
        View emailView = curView.findViewById(R.id.emailArea);
		IMUIHelper.setViewTouchHightlighted(phoneView);//设置手机按下时什么颜色
        IMUIHelper.setViewTouchHightlighted(emailView);//设置邮箱

			//发送邮件
      /*  emailView.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                if (currentUserId == IMLoginManager.instance().getLoginId())
                    return;
                IMUIHelper.showCustomDialog(getActivity(),View.GONE,String.format(getString(R.string.confirm_send_email),currentUser.getEmail()),new IMUIHelper.dialogCallback() {
                    @Override
                    public void callback() {
                        Intent data=new Intent(Intent.ACTION_SENDTO);
                        data.setData(Uri.parse("mailto:" + currentUser.getEmail()));
                        data.putExtra(Intent.EXTRA_SUBJECT, "");
                        data.putExtra(Intent.EXTRA_TEXT, "");
                        startActivity(data);
                    }
                });
            }
        });*/

		//打电话
		phoneView.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (currentUserId == IMLoginManager.instance().getLoginId())
					return;
                IMUIHelper.showCustomDialog(getActivity(),View.GONE,String.format(getString(R.string.confirm_dial),currentUser.getPhone()),new IMUIHelper.dialogCallback() {
                    @Override
                    public void callback() {
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                IMUIHelper.callPhone(getActivity(), currentUser.getPhone());
                            }
                        },0);
                    }
                });
			}
		});

		setSex(currentUser.getGender());//设置性别
	}

	private void setTextViewContent(int id, String content) {
		TextView textView = (TextView) curView.findViewById(id);
		if (textView == null) {
			return;
		}

		textView.setText(content);
	}

	/**
	 * 设置性别
	 * @param sex
	 */
	private void setSex(int sex) {
		if (curView == null) {
			return;
		}

		TextView sexTextView = (TextView) curView.findViewById(R.id.sex);//设置性别
		if (sexTextView == null) {
			return;
		}

		int textColor = Color.rgb(255, 138, 168); //xiaoxian
		String text = getString(R.string.sex_female_name);

		if (sex == DBConstant.SEX_MAILE) {
			textColor = Color.rgb(144, 203, 1);
			text = getString(R.string.sex_male_name);
		}

		if(sex == DBConstant.SEX_SECRET){
			textColor = Color.rgb(3, 3, 3);//设置颜色
			text = "密";
		}

		sexTextView.setVisibility(View.VISIBLE);
		sexTextView.setText(text);
		sexTextView.setTextColor(textColor);
	}


	/**
	 * 同步详细信息
	 */
	private void synchronousDetails(){
		setSex(RegisterSp.instance().getSpDetailedInfo().getDetailedSex());//设置性别
		setTextViewContent(R.id.telno, RegisterSp.instance().getSpDetailedInfo().getDetailedMobilePhone().toString());//设置手机
		setTextViewContent(R.id.email, RegisterSp.instance().getSpDetailedInfo().getDetailedEmail().toString());//设置邮箱
		setTextViewContent(R.id.nickName, RegisterSp.instance().getSpDetailedInfo().getDetailedNickName().toString());//设置昵称
	}

}
